/**
 * @file 路由守卫组件
 * @date 2025/11/07 17:26:46
 * @author lyqjob@yeah.net
 */

import {  useEffect  } from 'react';
import { useLocation, useNavigate } from 'react-router-dom';
import { useSelector } from 'react-redux';
import { checkPermission } from '@/utils/utils';

export const AuthRoute = ({ children }) => {
    const location = useLocation();
    const navigate = useNavigate();
    const { permission, asyncfiles } = useSelector(state => state.global);

    // const pathname = location.pathname.replace(/\/$/, '').split('?')[0];
    // console.log('pathname', pathname);
    // console.log('asyncfiles', asyncfiles);
    // 路由权限检查
    const whitelist = ['/','/login', '/404', '/403'];
    useEffect(() => {
        // 路由守卫逻辑
        if (!whitelist.includes(location.pathname)) {
            // 从asyncfiles中查找当前路由对应的权限
            const currentRoute = asyncfiles.find(item => item.path === location.pathname);
            const requiredPermission = currentRoute?.permission;
            // 如果权限不存在也跳转到403页面
            if (!requiredPermission) {
                navigate('/403', { replace: true });
            }
            // 如果路由需要权限且用户没有该权限
            if (requiredPermission && !checkPermission(requiredPermission, permission)) {
                navigate('/403', { replace: true });
            }
        }
    }, [location.pathname, navigate, permission, asyncfiles]);

    return children;
};